{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dfcd8d5c-8a7f-487a-bccb-3c901ebedb22",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from random import random\n",
    "from operator import add"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79661cde-0aba-4cef-8beb-cf7050464067",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from pyspark.sql import SparkSession\n",
    "from bigdl.ppml.utils.ppml_conf import PPMLConf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "677e3345-7ba9-4874-a525-f436fdd7b4f0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def square_2_random(_: int) -> float:\n",
    "    x = random() * 2 - 1\n",
    "    y = random() * 2 - 1\n",
    "    return 1 if x ** 2 + y ** 2 <= 1 else 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bf79de3-7168-4c5b-823c-6e664dbf19e8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "ppml_conf = (PPMLConf(k8s_enabled = True, sgx_enabled = True)\n",
    "        .setAppName(\"sgx-pyspark-pi-notebook-example\")\n",
    "        .set(\"spark.driver.memory\", \"1g\")\n",
    "        .set(\"spark.executor.cores\", \"8\")\n",
    "        .set(\"spark.executor.memory\", \"1g\")\n",
    "        .set(\"spark.executor.instances\", \"2\")\n",
    "        .set(\"spark.cores.max\", \"16\")\n",
    "        .set(\"spark.kubernetes.sgx.executor.jvm.mem\",\"3g\")\n",
    "        .set(\"spark.kubernetes.container.image.pullPolicy\",\"Always\")\n",
    "        .set(\"spark.kubernetes.sgx.driver.jvm.mem\",\"1g\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d103984-79cc-4c54-9c53-7663c7f4cc67",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "sc = SparkSession.builder.config(conf=(ppml_conf.conf())).getOrCreate()\n",
    "partiton_num = 2\n",
    "n = 100000 * partiton_num\n",
    "count = sc.sparkContext.parallelize(range(1, n + 1), partiton_num).map(square_2_random).reduce(add)\n",
    "sc.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17001509-90e6-46d4-b41b-547a0c774d4b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "print(\"Pi is roughly %f\" % (4.0 * count / n))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
